package com.mulanweb.api.module.controller.admin;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.api.module.model.Collection;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.validator.annotation.ValidateForm;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class CharteredController extends BaseController {

    @ValidateForm
    public void save() {
        String title = getPara("title");
        Long sellerId = getParaToLong("sellerId");
        Float price = Float.parseFloat(getPara("price"));
        Integer unitId = getParaToInt("unitId");
        Long cityId = getParaToLong("cityId");
        Integer profit = getParaToInt("profit");
        String description = getPara("description");
        String plateNumber = getPara("plateNumber");
        Long carBrandId = getParaToLong("carBrandId");
        int receptionNumber = getParaToInt("receptionNumber");
        String[] charteredType = getPara("charteredType").split(",");//包车，类型关联表信息
        String[] serverTime = getPara("serverTime").split(","); //包车，服务时间关联表
        String startTime = getPara("startTime");
        String endTime = getPara("endTime");
        Date createTime = new Date();
        Seller seller = Seller.dao.findById(sellerId);
        if (seller != null) {
            Chartered chartered = new Chartered();
            chartered.setTitle(title);
            chartered.setSellerId(sellerId);
            chartered.setPrice(price);
            chartered.setUnitId(unitId);
            chartered.setCityId(cityId);
            chartered.setDescription(description);
            chartered.setPlateNumber(plateNumber);
            chartered.setCarBrandId(carBrandId);
            chartered.setReceptionNumber(receptionNumber);
            chartered.setProfit(profit);
            chartered.setStartTime(DateUtil.strToDate(startTime, "hh:mm:ss"));
            chartered.setEndTime(DateUtil.strToDate(endTime, "hh:mm:ss"));
            /*chartered.setStartTime(strToDate(startTime));
            chartered.setEndTime(strToDate(endTime));*/

            chartered.setStatusId(3L);//司机状态默认为休息中
            chartered.setCreateTime(createTime);
            if (chartered.save()) {
                int i = 0;
                for (String tt : charteredType) {
                    CharteredJoinType charteredJoinType = new CharteredJoinType();
                    charteredJoinType.setCharteredId(chartered.getId());
                    charteredJoinType.setTypeId(Integer.parseInt(tt));
                    if (charteredJoinType.save()) {
                        i++;
                    }
                }
                int d = 0;
                for (String tt : serverTime) {
                    DriverJoinSt driverJoinSt = new DriverJoinSt();
                    driverJoinSt.setDriverId(chartered.getSellerId());
                    driverJoinSt.setServiceTimeId(Integer.parseInt(tt));
                    driverJoinSt.setCharteredId(chartered.getId());
                    driverJoinSt.setCreateTime(new Date());
                    if (driverJoinSt.save()) {
                        d++;
                    }
                }
                if (i == charteredType.length && d == serverTime.length)
                    returnSuccessJson(chartered.getId());
                else if (i != charteredType.length)
                    returnJson(0, "包车类型保存缺失");
                else if (d != serverTime.length)
                    returnJson(0, "司机服务时间保存缺失");
            } else {
                returnFailureJson();
            }
        } else {
            returnJson(0, "商家不存在");
        }
    }

    @ValidateForm
    public void update() {
        String title = getPara("title");
        String description = getPara("description");
        Float price = Float.parseFloat(getPara("price"));

        Chartered chartered = Chartered.dao.findById(getParaToLong("targetId"));
        if (chartered != null) {
            chartered.setTitle(title);
            chartered.setDescription(description);
            chartered.setPrice(price);
            if (chartered.update()) {
                returnSuccessJson(chartered.getId());
            } else {
                returnFailureJson();
            }
        }
    }

    @ValidateForm
    public void search() {
        SQLGenerateHelper helper = new SQLGenerateHelper("chartered", "create_time desc");
        Integer typeId = getParaToInt("typeId");
        if (typeId != null) {
            List<CharteredJoinType> charteredJoinType = CharteredJoinType.dao.find("SELECT * FROM chartered_join_type WHERE type_id=?", typeId);
            List<Integer> charteredIds = new ArrayList<Integer>(charteredJoinType.size());
            for (CharteredJoinType cc : charteredJoinType) {
                charteredIds.add(Integer.parseInt(cc.getCharteredId() + ""));
            }
            if (charteredIds.size() > 0) {
                helper.addInCondition("id", charteredIds);
            } else {
                charteredIds.add(0);
                helper.addInCondition("id", charteredIds);
            }
        }
        helper.addLikeCondition("title", getPara("title"));
        helper.addIsNullCondition("delete_time");
        Page<Chartered> page = Chartered.dao.paginate(getPageNumber(), getPageSize(), helper.getSqlSelect(), helper.getSqlExceptSelect(), helper.getQueryParas());
        returnPageModelJson(page);
    }

    @ValidateForm
    public void getDetail() {
        Integer charteredId = getParaToInt("targetId");
        Chartered chartered = Chartered.dao.findById(charteredId);
        if (StrKit.notNull(chartered)) {
            Seller seller = Seller.dao.findById(chartered.getSellerId());
            AllType allType = AllType.dao.findById(seller.getCategoryId());
            List<Collection> collections = Collection.dao.find("SELECT * FROM collection WHERE type_id=24 AND target_id=?", chartered.getId());
            List<ContentEvaluate> evaluates = ContentEvaluate.dao.find("SELECT * FROM content_evaluate WHERE type_id=24 AND target_id=?", chartered.getId());
            List<Photo> photos = Photo.dao.find("SELECT * FROM photo WHERE type_id in (15,16) AND target_id=? ORDER BY type_id DESC", chartered.getId());
            List<String> photoPaths = new ArrayList<String>(photos.size());
            for (Photo pp : photos) {
                photoPaths.add(pp.getPath());
            }
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> target = new HashMap<String, Object>();
            target.put("sellerName", seller.getSellerName());
            target.put("sellerCategory", allType.getName());
            target.put("score", chartered.countScore());
            target.put("collectionNumber", collections.size());
            target.put("evaluateNumber", evaluates.size());
            target.put("cityName", City.dao.findById(chartered.getCityId()).getNameCn());
            target.put("price", chartered.getPrice());
            target.put("description", chartered.getDescription());
            target.put("personNumber", chartered.getReceptionNumber());
            target.put("title",chartered.getTitle());
            target.put("photos", photoPaths);
            map.put("ReturnCode", 1);
            map.put("ReturnStr", "操作成功");
            map.put("target", target);
            renderJson(map);
        } else {
            returnFailureJson();
        }
    }

    @ValidateForm
    public void delete() {
        Integer charteredId = getParaToInt("targetId");
        Chartered chartered = Chartered.dao.findById(charteredId);
        if (StrKit.notNull(chartered != null)) {
            chartered.setDeleteTime(new Date());
            if (chartered.update()) {
                returnSuccessJson();
            } else {
                returnFailureJson();
            }
        } else {
            returnJson(0, "对象不存在");
        }
    }



   /* public Date strToDate(String time) {
        DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
        try {
            Date date = sdf.parse(time);
            System.out.println("Date and Time: " + date);
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/
}
